/**
 * 处理异常 let [err,res] = await handleError(asyncFunc)
 * @param asyncFunc
 * @return {Promise<*[]>}
 */
export async function handleError<T>(asyncFunc: () => Promise<T>): Promise<[null, T] | [Error, null]> {
    try {
        let res: T = await asyncFunc()
        return [null, res]
    } catch (e: any) {
        return [e, null]
    }
}


/**
 * 深度拷贝
 * @param obj
 * @constructor
 */
export function cloneDeep<T>(obj: T): T {
    if (obj === null || typeof obj !== 'object') {
        // 如果是基本类型或null，直接返回
        return obj;
    }

    if (Array.isArray(obj)) {
        // 如果是数组，递归复制数组元素
        const copyArray: any[] = [];
        for (const item of obj) {
            copyArray.push(cloneDeep(item));
        }
        return copyArray as T;
    }

    // 如果是对象，递归复制对象属性
    const copyObj: Record<string, any> = {};
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            copyObj[key] = cloneDeep(obj[key]);
        }
    }
    return copyObj as T;
}

/**
 * 判断是否为空的数组
 */
export function isNotEmptyArray(arr: any[] | undefined) {
    return !!(arr && Array.isArray(arr) && arr.length > 0);
}

/**
 * 初始化pageQuery
 * @param pageQuery
 */
// {order: {id: 'asc'}}
export function initPageQuery<T>(pageQuery?: Partial<PageQuery<T>>): PageQuery<T> {
    const defaultPageQuery: PageQuery<T> = {
        pageSize: 10,
        currentPage: 1,
        query: {},
        order: {},
        relations: {},
        cache: true,
    }
    if (!pageQuery) {
        pageQuery = defaultPageQuery
    }
    return {
        ...defaultPageQuery,
        ...pageQuery
    }
}

/**
 * 原版的promise.allSettled
 * @param values
 * @constructor
 */
export function PromiseAll<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>> }> {
    return Promise.allSettled(values)
}

/**
 * 睡眠函数
 * @param timeout
 * @param value
 */
export function sleep(timeout = 1000, value?: any) {
    return new Promise((resolve) => {
        setTimeout(resolve, timeout, value)
    })
}


/**
 * 获取[min,max]之间的随机数
 * @param min
 * @param max
 */
export function getRandomFrom(min = 1, max = 100) {
    const choices = max - min + 1;
    return Math.floor(Math.random() * choices + min);
}

/**
 * 防抖
 */